package com.analysis.controller;

import com.analysis.dto.ApiResponse;
import com.analysis.entity.Version;
import com.analysis.enums.RequireLogin;
import com.analysis.service.VersionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/api/version")
@CrossOrigin(origins = "*")
public class VersionController {

    @Autowired
    private VersionService versionService;

    @PostMapping("/add")
    @RequireLogin
    public ApiResponse<Version> add(@RequestBody Version version) {
        try {
            if (version.getName() == null || version.getName().trim().isEmpty()) {
                return ApiResponse.error("版本名称不能为空");
            }
            int result = versionService.create(version);
            if (result > 0) {
                return ApiResponse.success(version);
            }
            return ApiResponse.error("创建版本失败");
        } catch (Exception e) {
            return ApiResponse.error("创建版本异常: " + e.getMessage());
        }
    }

    @PostMapping("/delete")
    @RequireLogin
    public ApiResponse<String> delete(@RequestParam Long id) {
        try {
            int result = versionService.delete(id);
            if (result > 0) {
                return ApiResponse.success("删除成功");
            }
            return ApiResponse.error("删除失败或不存在");
        } catch (Exception e) {
            return ApiResponse.error("删除版本异常: " + e.getMessage());
        }
    }

    @PostMapping("/update")
    @RequireLogin
    public ApiResponse<String> update(@RequestBody Version version) {
        try {
            if (version.getId() == null) {
                return ApiResponse.error("ID不能为空");
            }
            int result = versionService.update(version);
            if (result > 0) {
                return ApiResponse.success("更新成功");
            }
            return ApiResponse.error("更新失败");
        } catch (Exception e) {
            return ApiResponse.error("更新版本异常: " + e.getMessage());
        }
    }

    @GetMapping("/get")
    @RequireLogin
    public ApiResponse<Version> get(@RequestParam Long id) {
        try {
            Version version = versionService.getById(id);
            if (version != null) {
                return ApiResponse.success(version);
            }
            return ApiResponse.error("未找到版本");
        } catch (Exception e) {
            return ApiResponse.error("查询版本异常: " + e.getMessage());
        }
    }

    @GetMapping("/list")
    @RequireLogin
    public ApiResponse<List<Version>> list() {
        try {
            return ApiResponse.success(versionService.listAll());
        } catch (Exception e) {
            return ApiResponse.error("查询版本列表异常: " + e.getMessage());
        }
    }
}


